package com.lbj.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbj.mall.common.constant.ProductUp;
import com.lbj.mall.common.entity.common.spu.*;
import com.lbj.mall.common.entity.to.SkuReductionTo;
import com.lbj.mall.common.entity.to.SpuBoundTo;
import com.lbj.mall.common.entity.vo.SkuUpVo;
import com.lbj.mall.common.utils.PageUtils;
import com.lbj.mall.common.utils.Query;
import com.lbj.mall.common.utils.R;
import com.lbj.mall.product.dao.SpuInfoDao;
import com.lbj.mall.product.entity.*;
import com.lbj.mall.product.feign.CouponFeign;
import com.lbj.mall.product.feign.SearchFeign;
import com.lbj.mall.product.feign.WareFeign;
import com.lbj.mall.product.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeign couponFeign;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeign wareFeign;
    @Autowired
    private SearchFeign searchFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 保存SPU大信息
     */
    @Transactional
    @Override
    public void saveSpu(SpuSaveVO spuSaveVO) {
        // 1、保存spu基本信息：pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        this.insertBaseSPUInfo(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();

        // 2、保存spu的描述图片：pms_spu_info_desc
        List<String> decript = spuSaveVO.getDecript();
        if (decript != null && decript.size() > 0) {
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            // 当spuInfoEntity被保存到数据库时，spuInfoEntity中就保存了id属性
            spuInfoDescEntity.setSpuId(spuId);
            // String.join：将集合中的每个元素用“，”拼接起来
            spuInfoDescEntity.setDecript(String.join(",", decript));
            spuInfoDescService.save(spuInfoDescEntity);
        }

        // 3、保存spu的图片集：pms_spu_images
        spuImagesService.saveImages(spuId, spuSaveVO.getImages());

        // 4、保存spu的规则参数：pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueList = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity entity = new ProductAttrValueEntity();
            entity.setSpuId(spuId);
            entity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            entity.setAttrName(attrEntity.getAttrName());
            entity.setAttrValue(item.getAttrValues());
            entity.setQuickShow(item.getShowDesc());
            return entity;
        }).collect(Collectors.toList());
        if (productAttrValueList.size() > 0) {
            productAttrValueService.saveBatch(productAttrValueList);
        }

        // 5、调用远程服务保存spu的积分信息：库mall_sms => sms_spu_bounds
        Bounds bounds = spuSaveVO.getBounds();
        if (new BigDecimal(0).compareTo(bounds.getBuyBounds()) <= 0
                || new BigDecimal(0).compareTo(bounds.getGrowBounds()) <= 0) {
            SpuBoundTo spuBoundTo = new SpuBoundTo();
            BeanUtils.copyProperties(bounds, spuBoundTo);
            spuBoundTo.setSpuId(spuId);
            R saveBoundResult = couponFeign.saveSpuBound(spuBoundTo);
            if (0 != saveBoundResult.getCode()) {
                log.error("远程服务->保存积分信息->失败");
            }
        }

        // 6、保存当前spu对应的所有sku信息
        List<Skus> skuList = spuSaveVO.getSkus();
        if (skuList != null && skuList.size() > 0) {
            skuList.forEach(item -> {
                String defaultImg = "";
                for (Images images : item.getImages()) {
                    if (images.getDefaultImg() == 1) {
                        defaultImg = images.getImgUrl();
                        break;
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                // 6.1、保存sku的基本信息：pms_sku_info
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesList = item.getImages().stream()
                        .filter(images -> !StringUtils.isEmpty(images.getImgUrl()))
                        .map(image -> {
                            SkuImagesEntity entity = new SkuImagesEntity();
                            entity.setSkuId(skuId);
                            entity.setImgUrl(image.getImgUrl());
                            entity.setDefaultImg(image.getDefaultImg());
                            return entity;
                        }).collect(Collectors.toList());
                // 6.2、保存sku的图片信息：pms_sku_images
                if (skuImagesList.size() > 0) {
                    skuImagesService.saveBatch(skuImagesList);
                }

                List<Attr> attrList = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueList = attrList.stream().map(attr -> {
                    SkuSaleAttrValueEntity entity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, entity);
                    entity.setSkuId(skuId);
                    return entity;
                }).collect(Collectors.toList());
                // 6.3、保存sku的销售属性信息：pms_sku_sale_attr_value
                if (skuSaleAttrValueList.size() > 0) {
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);
                }

                // 6.4 保存sku的优惠满减等信息：
                // 库mall_sms:sms_sku_ladder/sms_sku_full_reduction/sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                R result = couponFeign.saveSkuReductionInfo(skuReductionTo);
                log.info("远程服务->保存优惠信息-> {}", result);
                if (0 != result.getCode()) {
                    log.error("远程服务->保存优惠信息->失败");
                }
            });
        }
    }

    @Override
    public void insertBaseSPUInfo(SpuInfoEntity spuInfoEntity) {
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
    }

    /**
     * 按照条件查询
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(item -> {
                item.eq("id", key).or().like("spu_name", key);
            });
        }
        String categoryId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(categoryId) && !"0".equals(categoryId))
            wrapper.eq("catalog_id", categoryId);
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId))
            wrapper.eq("brand_id", brandId);
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status))
            wrapper.eq("publish_status", status);
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * 上架
     */
    @Transactional
    @Override
    public void spuUp(Long spuId) {
        // 在外面查是为了避免在循环中查询同一个内容
        // 这里要避免连表查询是因为数据量大的情况下，连表查询会浪费性能

        // 2.4.1 根据spuId查询所有可以被检索的属性
        List<ProductAttrValueEntity> attrValueList = productAttrValueService.getBaseListForSpuId(spuId);
        // 2.4.2 收集所有的attr_id
        List<Long> attrIdList = attrValueList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        // 2.4.3 去attr属性表中查询所有可以被检索的属性
        List<Long> canSearchAttrIdList = attrService.queryCanSearchAttrId(attrIdList);
        // 2.4.4 再根据可被检索的属性再次查询pms_product_attr_value表获取对应的属性
        List<ProductAttrValueEntity> productAttrValueList = attrValueList.stream()
                .filter(item -> canSearchAttrIdList.contains(item.getAttrId()))
                .collect(Collectors.toList());
        // 2.4.5 根据所有可被检索的属性获取要传给es的属性
        List<SkuUpVo.Attr> attrList = productAttrValueList.stream().map(item -> {
            SkuUpVo.Attr attr = new SkuUpVo.Attr();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());

        // 1.根据spuId查询所有的sku -- pms_sku_info
        List<SkuInfoEntity> skuInfoList = skuInfoService.queryAllSkuBySpuId(spuId);

        // 2.5.1 获取所有skuId
        List<Long> wareFeignRequestSkuIds = skuInfoList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // 2.5.2 远程调用库存服务
        List<LinkedHashMap<String, Object>> hasStockToList = null;
        try {
            R hasStockR = wareFeign.hasStock(wareFeignRequestSkuIds);
            log.debug("查看库存返回的数据：" + hasStockR);
            hasStockToList = (List<LinkedHashMap<String, Object>>) hasStockR.get("data");
        } catch (Exception e) {
            log.error("调用远程库存服务失败：" + e);
        }

        // 所有需要上架的sku信息
        List<LinkedHashMap<String, Object>> finalHasStockToList = hasStockToList;
        List<SkuUpVo> upProductList = skuInfoList.stream().map(item -> {
            // 2.将查询来的所有对应的sku和我们需要组装的sku属性对拷
            SkuUpVo vo = new SkuUpVo();
            BeanUtils.copyProperties(item, vo);
            // 2.1 设置skuImg、price
            vo.setSkuImg(item.getSkuDefaultImg());
            vo.setSkuPrice(item.getPrice());

            // 2.2 设置热度评分
            vo.setHotScore(0L);

            // 2.3 设置 brandName、brandImg、catalogName
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            vo.setBrandName(brandEntity.getName());
            vo.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            vo.setCatalogName(categoryEntity.getName());

            // 2.4 设置当前sku对应的所有可被检索的属性:attrId/attrName/attrValue
            vo.setAttrs(attrList);

            // 2.5 hasStock：远程调用ware服务获取是否有库存
            if (finalHasStockToList == null) {
                vo.setHasStock(true);
            } else {
                boolean isHasStock = false;
                for (LinkedHashMap map : finalHasStockToList) {
                    if (map != null && map.get("skuId") != null) {
                        if (Objects.equals(item.getSkuId(), map.get("skuId"))) {
                            if (map.get("hasStock") == null) {
                                isHasStock = true;
                            } else {
                                isHasStock = (int) map.get("hasStock") > 0;
                            }
                        }
                    }
                }
                vo.setHasStock(isHasStock);
            }
            return vo;
        }).collect(Collectors.toList());

        // TODO 发送远程服务，将es模型发送到search远程服务中保存es数据
        R r = searchFeign.saveProduct(upProductList);

        if (r.getCode() == 0) {
            // 修改sku的上架属性
            SpuInfoEntity entity = new SpuInfoEntity();
            entity.setId(spuId);
            entity.setPublishStatus(ProductUp.UP.getCode());
            updateById(entity);
        } else {
            // TODO 错误时要考虑重试机制等
            log.error("远程上架spu失败");
        }
    }

    /**
     * 根据skuId查询spu的信息
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        //先查询sku表里的数据
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);

        //获得spuId
        Long spuId = skuInfoEntity.getSpuId();

        //再通过spuId查询spuInfo信息表里的数据
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);

        //查询品牌表的数据获取品牌名
        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        spuInfoEntity.setBrandName(brandEntity.getName());

        return spuInfoEntity;
    }
}